home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C/C++ Users Group Library 1996 July
/
C-C++ Users Group Library July 1996.iso
/
listings
/
v_12_08
/
letters
/
pstring.c
< prev
next >
Wrap
C/C++ Source or Header
|
1994-06-20
|
3KB
|
88 lines
@CSOURCE6 = /*<R>
* Module: pstring.c (string handling support)<R>
* by Martin.Weitzel@rent-a-guru.DE<R>
*/<R>
#include "pstring.h"<R>
#include <<stdarg.h>><R>
#include <<stdlib.h>><R>
#include <<string.h>><R>
/*<R>
* The macros ALLOC and FREE hide away some casts<R>
* (necessary to suppress compiler-warnings) and<R>
* care for pre-ANSI/ISO-C free() which is not<R>
* guaranteed to be safe for (void *)0-pointers.<R>
*/<R>
#define ALLOC(n, t) ((t *)malloc((n)*(sizeof(t))))<R>
#if __STDC__ == 1<R>
#define FREE(p) free((void *)p)<R>
#else<R>
#define FREE(p) if (p) free((void *)p)<R>
#endif<R>
<R>
/*<R>
* Concatenate variable number of strings in space<R>
* allocated from the heap. If no more space is<R>
* available, the program is aborted.<R>
*/<R>
char *pstr_x(const char *str, ...) {<R>
const char *cp; /* tmpry to step over args */<R>
char *result; /* tmpry for return value */<R>
va_list ap; /* arglist iterator */<R>
size_t len = 1; /* total length of strs + 1 */<R>
/*<R>
* loop over args, sum length of all strs<R>
*/<R>
va_start(ap, str); <R>
for (cp = str; cp; cp = va_arg(ap, const char *))<R>
len += strlen(cp);<R>
va_end(ap);<R>
/*<R>
* allocate space for all strs<R>
*/<R>
if ((result = ALLOC(len, char)) == (char *)0)<R>
abort();<R>
result[0] = '\0';<R>
/*<R>
* loop over args, concatenate all strs<R>
*/<R>
va_start(ap, str); <R>
for (cp = str; cp; cp = va_arg(ap, const char *))<R>
(void) strcat(result, cp);<R>
va_end(ap);<R>
return result;<R>
}<R>
<R>
/*<R>
* Helper function for building temporary strings<R>
* (see "TMPSTR"-macros in "pstring.h" for details).<R>
* It effectively "schedules a free" delayed by one<R>
* call to this function, so the caller does not have<R>
* to care for saving the result of "strmake" in a<R>
* variable and hand this to free later on.<R>
* Note: With "(void) tmpstr((char *)0)" you may<R>
* force to de-allocate the last temporary string<R>
* build with one of the "TMPSTR"-macros.<R>
*/<R>
char *tmpstr(char *str) {<R>
static char *laststr;<R>
FREE(laststr);<R>
return laststr = str;<R>
}<R>
<R>
/*<R>
* He<%-2>lper function for copying to pointers initialized<R>
<%0> * by calls to the "pstr_"-function and macros.<R>
* N<%-2>ote: "pstrcpy" takes the ADDRESS of a char pointer<%0><R>
* as its first argument and automatic char pointer<R>
* variables MUST be initialized with (char *)0 prior<R>
* handing their address to this function the first<R>
* time.<R>
*/<R>
void pstrcpy(char **destp, const char *src) {<R>
FREE(*destp);<R>
*destp = pstr_1(src);<R>
}<R>
<R>
/* End of File */